<template>
  <form>
    <table>
      <tbody>
        <tr>
          <td>姓名：</td>
          <td>
            <input type="text" v-model="teacher.teacherName" />
          </td>
        </tr>

        <tr>
          <td>年龄：</td>
          <td>
            <input type="text" v-model="teacher.teacherAge" />
          </td>
        </tr>

        <tr>
          <td>性别：</td>
          <td>
            <input type="text" v-model="teacher.teacherSex" />
          </td>
        </tr>

        <tr>
          <td>联系方式：</td>
          <td>
            <input type="text" v-model="teacher.phone" />
          </td>
        </tr>

        <tr>
          <td>教学班级：</td>
          <td>
            <input type="text" v-model="teacher.className" />
          </td>
        </tr>

        <tr id="btn">
          <td colspan="2">
            <input type="button" value="保存" @click="save" />
            <input type="button" value="取消" @click="$router.push('/')" />
          </td>
        </tr>
      </tbody>
    </table>
  </form>
</template>

<style scoped>
input {
  padding: 5px;
  margin: 5px;
}

form {
  text-align: center;
}

table tr td:first-child {
  text-align: right;
}

#btn td {
  text-align: center;
}
</style>

<script setup>
import { useRoute } from 'vue-router'
import { onMounted, ref } from 'vue'
import axios from 'axios'

const route = useRoute()

// 后端api
const api = 'http://localhost:8000/teachers'

// 老师对象
const teacher = ref({
  className: '',
  phone: '',
  teacherAge: '',
  teacherName: '',
})

onMounted(() => {
  // 请求
  axios.get(`${api}/${route.params.id}`).then((res) => {
    if (res.status === 200) {
      teacher.value = res.data.data
    }
  })
})

// 修改
function save() {
  // 修改请求
  axios.put(`${api}/${route.params.id}`, teacher.value).then((res) => {
    if (res.status === 200) {
      setTimeout(() => {
        location.href = '/'
      }, 100)
    }
  })
}
</script>
